/**
 * 
 */
package net.phoenix.repository.query.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexNotFoundException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.SnapshotDeletionPolicy;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.core.io.Resource;

/**
 * @author lixf
 * 
 */
public class LuceneQueryConfig {
	private QueryParser queryParser;
	private Directory directory;
	private IndexReader reader;

	public LuceneQueryConfig() {

	}

	public void close() throws IOException {
		this.reader.close();
		this.directory.close();
	}

	public void setIndexPath(Resource path) throws IOException {
		try {
			this.directory = FSDirectory.open(path.getFile());
			this.reader = IndexReader.open(this.directory, true);
		} catch (IndexNotFoundException infe) {
			Analyzer a = new StandardAnalyzer(Version.LUCENE_36);
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, a);
			config.setOpenMode(OpenMode.CREATE_OR_APPEND);
			IndexWriter writer = new IndexWriter(directory, config);
			writer.commit();
			writer.close();
			this.directory = FSDirectory.open(path.getFile());
			this.reader = IndexReader.open(this.directory, true);
		}
	}

	public void setQueryParser(QueryParser parser) {
		this.queryParser = parser;
	}

	public QueryParser getQueryParser() {
		return queryParser;
	}

	public IndexSearcher createSearcher() throws IOException {
		return new IndexSearcher(this.reader);
	}

}
